package concurrent.chapter13;

import java.util.LinkedList;

public class MessageQueue {
    private final LinkedList<Message> queue;
    private final static int DEFAULT_MAX_LIMIT = 0;
    private final int limit;

    public MessageQueue() {
        this(DEFAULT_MAX_LIMIT);
    }

    public MessageQueue(final int limit) {
        this.limit = limit;
        this.queue = new LinkedList<>();

    }

    public void put(Message message) throws InterruptedException {
        //queue是共享数据，要保护
        synchronized (queue) {
            queue.wait();
        }
        queue.addLast(message);
        queue.notifyAll();
    }

    public Message take() throws InterruptedException {
        synchronized (queue) {
            while (queue.isEmpty()) {
                queue.wait();
            }
            Message message = queue.removeFirst();
            queue.notifyAll();
            return message;
        }
    }

    //一次写，没有必要加锁
    public int getMaxLimit() {
        return this.limit;
    }

    public int getMessageSize() {
        synchronized (queue) {
            return queue.size();
        }
    }
}
